package com.leyou.upload.service;

import com.gitee.yongzhuzl.commonutil.util.empty.EmptyUtil;
import com.gitee.yongzhuzl.commonutil.util.file.FileUtil;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.upload.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * description: 上传文件业务
 * @author 朱正磊
 * @date 2021-03-29 01:04:46
 */
@Slf4j
@Service
public class UploadService {

    @Resource
    private FastFileStorageClient storageClient;

    @Resource
    private UploadProperties prop;

    /**
     * description: 上传图片
     * @author 朱正磊
     * @date 2021-03-29 01:06:45
     * @param file 图片对象
     * @return 返回图片存储的地址
     */
    public String uploadImage(MultipartFile file) {
        try {
            // 校验文件类型
            String contentType = file.getContentType();
            if (!prop.getAllowTypes().contains(contentType)) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }

            // 校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (EmptyUtil.isEmpty(image)) {
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }

            // 上传文件到FastDFS
            String extension = FileUtil.getFileNameExtension(file.getOriginalFilename());
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

            // 返回文件上传路径
            return prop.getBaseUrl() + storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上传】上传文件失败：", e);
            throw new LyException(ExceptionEnum.UPLOAD_FILE_ERROR);
        }
    }

}
